﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.Permission.Interface;
using Microhard.Permission;
using Microhard.Permission.Models;
using Microhard.Core.DBUtility;
using Microhard.Core;


namespace Microhard.Permission_MembershipImpl
{
    public class ResouceImpl : IResouce
    {
        #region IRepository<Resouce> Members

        public ExecutedResult Add(Permission.Models.Resouce model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var toAdd = model.ToEntity();
            toAdd.ResourceID = Guid.NewGuid();
            toAdd.ParentResourceID = null;
            db.MicroHard_Resources.InsertOnSubmit(toAdd);

            try
            {
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("Resource.Add", "添加资源失败，请联系系统管理员");
                Log.Error("Resource.Add", ex);
            }

            return rtn;
        }

        public ExecutedResult Update(Permission.Models.Resouce model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            MicroHard_Resource entity = db.MicroHard_Resources.SingleOrDefault(c => c.ResourceID == model.ResourceID);

            if (entity != null)
            {
                entity.Description = model.Description;
                entity.Name = model.Name;
                entity.KeyName = model.KeyName;
                entity.ResourceTypeID = model.ResourceTypeID;
                entity.Status = model.Status;
                entity.AllowGroupID = model.AllowGroupID;
            }
            try
            {
                db.SubmitChanges();
                rtn.Scope.IsSysManage = true;
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("Resource.Update", "修改资源失败，请联系系统管理员");
                Log.Error("Resource.Update", ex);
            }
            return rtn;
        }

        public ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var toDeltes = from b in db.MicroHard_Resources
                           where ids.Contains(b.ResourceID)
                           select b;
            foreach (var d in toDeltes)
            {
                //是否被使用
                int cnt = db.MicroHard_Permissions.Count(p => p.ResID == d.ResourceID);
                if (cnt > 0)
                {
                    result.ErrorMsg.Add(d.ResourceID.ToString(), "资源:" + d.Name + "正在使用中，无法删除");
                    continue;

                }
                db.MicroHard_Resources.DeleteOnSubmit(d);
            }
            if (result.ErrorMsg.Count == 0)
            {
                try
                {

                    db.SubmitChanges();

                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add("Resource.Delete", ex.Message);
                }
            }
            return result;
        }

        public Resouce GetModelByID(Guid id)
        {
            if (id == Guid.Empty)
                return null;

            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var rtn = db.MicroHard_Resources.SingleOrDefault(p => p.ResourceID == id);

            if (rtn != null)
                return rtn.ToModel();

            return null;
        }

        public List<Permission.Models.Resouce> Query(Permission.Models.Resouce Model, int pageIndex, int pageSize, out int totalCount)
        {
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            IEnumerable<MicroHard_Resource> entities = null;
            if (Model.ResourceTypeID != Guid.Empty)
            {
                entities = from b in db.MicroHard_Resources
                           where b.MicroHard_ResourceType.ResourceTypeID == Model.ResourceTypeID
                           select b;
            }
            else
            {
                entities = from b in db.MicroHard_Resources
                           select b;
            }
            totalCount = entities.Count();
            var pagedEntities = entities.OrderByDescending(p => p.MicroHard_ResourceType.Name).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return pagedEntities.Select(p => p.ToModel()).ToList();
        }

        public List<Permission.Models.Resouce> Query(Permission.Models.Resouce Model)
        {
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var rtn = (from r in db.MicroHard_Resources
                       where r.ParentResourceID == null
                       select r).OrderBy(r => r.MicroHard_ResourceType.ResourceTypeID).Select(r => r.ToModel()).ToList();
            return rtn;
        }

        public ExecutedResult Delete(Resouce model)
        {
            ExecutedResult rtn = new ExecutedResult();
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var entity = db.MicroHard_Resources.SingleOrDefault(c => c.ResourceID == model.ResourceID);
            if (entity != null)
            {
                db.MicroHard_Resources.DeleteOnSubmit(entity);
            }
            try
            {
                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("Resource.Delete", "删除资源失败，请联系系统管理员");
                Log.Error("Resource.Delete", ex);
            }
            return rtn;
        }
        #endregion



        #region IResouce Members

        public ExecutedResult DeleteValidation(Guid deleteId)
        {
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            ExecutedResult rtn = new ExecutedResult();
            var entity = db.MicroHard_Resources.SingleOrDefault(r => r.ResourceID == deleteId);
            if (entity != null)
            {
                if (entity.ResourcesChild != null && entity.ResourcesChild.Count > 0)
                {
                    rtn.ErrorMsg.Add(entity.ResourceID.ToString(), "资源\"" + entity.Name + "\"拥有子资源,无法删除");
                }
            }
            return rtn;
        }

        #endregion

        #region IRepository<Resouce> Members


        public Resouce GetModelByModel(Resouce model)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IResouce Members


        public bool IsKeyNameDuplicate(Resouce model)
        {
            if (!string.IsNullOrEmpty(model.KeyName))
            {
                MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
                var cnt = db.MicroHard_Resources.Count(r => r.KeyName.ToLower() == model.KeyName.ToLower());
                if (cnt > 0)
                    return true;
            }
            return false;
        }

        #endregion

        #region IRepository<Resouce> Members


        public ScopeResult scope
        {
            get;
            set;
        }

        #endregion
    }
}
